import {loginWechat, refreshToken, registryWechat} from "@/server/user/user";
import store from "@/store";

const user = {
    namespaced: true,

    state: {
        token: null,
        id: null,
        inviteId: null,
        nickname: null,
        realName: null,
        avatar: require('@/assets/img/userDefaultAvatar.jpeg'),
        role: '0',
        vipExpire: null,
        trialNum: 0
    },

    mutations: {
        // 更新传入的字段
        update(state, data) {
            for (const column in data) {
                if (!data[column]) {
                    continue
                }
                
                state[column] = data[column]
            }
        },
        // 清空vip信息
        clearVip(state) {
            state.vipExpire = null
        },
    },

    actions: {
        // 微信注册
        registryWechat({commit, dispatch}, code) {
            registryWechat(code).then(res => {
                // 缓存用户信息
                commit('update', res.data)
                dispatch('setVipExpireInterval')
                dispatch('setRefreshTokenInterval')
            })
        },

        // 微信登录
        loginWechat({commit, dispatch}, code) {
            loginWechat(code).then(res => {
                if (!res.data) {
                    return
                }

                // 缓存用户信息
                commit('update', res.data)
                dispatch('setVipExpireInterval')
                dispatch('setRefreshTokenInterval')
            })
        },
        // 每25分钟定时请求后台，刷新登录态
        setRefreshTokenInterval() {
            setInterval(() => {
                refreshToken().then(() => {
                })
            }, 25 * 60 * 1000)
        },
        // 监空vip过期时间，过期置空
        setVipExpireInterval({state, commit}) {
            // 设置定时任务
            setInterval(() => {
                if (!state.vipExpire) {
                    return
                }

                const currentTime = new Date().getTime()
                // 已经过期
                if (currentTime >= state.vipExpire) {
                    commit("user/clearVip")
                }
            }, 1000);
        }
    },

    getters: {
        // 是否已登录
        isLogin(state) {
            return state.token
        },
        // 是否是vip
        isVip(state) {
            return state.vipExpire
        },
        // 是否是代理
        isAgent(state) {
            return state.role === '1'
        },
        // 可以发送消息
        canSendPrompt(state) {
            return store.getters["user/isVip"] || state.trialNum > 0
        }
    }
};

export default user;
